//
//  WYUserAccount.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/10.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit

//归档  遵守 NSCoding 协议
class WYUserAccount: NSObject , NSCoding {
    
    //用户授权唯一票据
    var access_token: String?
  
    //access_token 的生命周期 也就授权时间
    var expires_in: NSTimeInterval = 0 {
        
        didSet{
        
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    //过期时间
    var expiresDate: NSDate?
    //授权用户 id
    var uid: Int64 = 0
    //用户名
    var name: String?
    //构造函数
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
       
     super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //
    override var description: String {
    
        let keys = ["uid", "access_token", "name", "avatar_large", "expires_in"]
        
        //该方法是输入的是数组 返回 :的是字典 description 是描述字典 key 对应的 value
        //外界就可以那到
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //MARK -- 归档解档的方法
    func encodeWithCoder(aCoder: NSCoder) {
        
        //储存函数 通过 什么样的 key 来储存
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //解档
     required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    
    }
    
    //保存用户对象
    func saveUserAccount() -> Bool {
    
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")

        print(path)
        let result = NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
        
        return result;
        


    }

    //通过路径读取用户对象
    class func loadUserAccount() -> WYUserAccount? {
    
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
        
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? WYUserAccount
    }





}